<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="计划名称" prop="planId">
        <el-select
          v-model="queryParams.planId"
          placeholder="请选择评价计划"
          clearable
          filterable
          class="!w-240px"
        >
          <el-option
            v-for="plan in planList"
            :key="plan.id"
            :label="plan.planName"
            :value="plan.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="身份证号" prop="idNumber">
        <el-input
          v-model="queryParams.idNumber"
          placeholder="请输入身份证号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input
          v-model="queryParams.mobile"
          placeholder="请输入手机号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="申报职业" prop="appliedProfession">
        <el-input
          v-model="queryParams.appliedProfession"
          placeholder="请输入申报职业"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="申报等级" prop="appliedLevel">
        <el-select
          v-model="queryParams.appliedLevel"
          placeholder="请选择申报等级"
          clearable
          class="!w-240px"
        >
          <el-option label="五级" value="五级" />
          <el-option label="四级" value="四级" />
          <el-option label="三级" value="三级" />
          <el-option label="二级" value="二级" />
          <el-option label="一级" value="一级" />
        </el-select>
      </el-form-item>
      <el-form-item label="报名状态" prop="registrationStatus">
        <el-select
          v-model="queryParams.registrationStatus"
          placeholder="请选择报名状态"
          clearable
          class="!w-240px"
        >
          <el-option label="待报名" :value="0" />
          <el-option label="已报名" :value="1" />
          <el-option label="已取消" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态" prop="auditStatus">
        <el-select
          v-model="queryParams.auditStatus"
          placeholder="请选择审核状态"
          clearable
          class="!w-240px"
        >
          <el-option label="待审核" :value="0" />
          <el-option label="审核通过" :value="1" />
          <el-option label="审核不通过" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['eval:candidate:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="info"
          plain
          @click="handleImport"
          v-hasPermi="['eval:candidate:import']"
        >
          <Icon icon="ep:upload" class="mr-5px" /> 导入
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['eval:candidate:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
          type="warning"
          plain
          @click="openBatchAudit"
          v-hasPermi="['eval:candidate:audit']"
          :disabled="!multipleSelection.length"
        >
          <Icon icon="ep:check" class="mr-5px" /> 批量审核
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table 
      v-loading="loading" 
      :data="list" 
      :stripe="true" 
      :show-overflow-tooltip="true"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="姓名" align="center" prop="name" width="100" />
      <el-table-column label="身份证号" align="center" prop="idNumber" width="180" />
      <el-table-column label="手机号" align="center" prop="mobile" width="120" />
      <el-table-column label="性别" align="center" prop="gender" width="60">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.SYSTEM_USER_SEX" :value="scope.row.gender" />
        </template>
      </el-table-column>
      <el-table-column label="出生日期" align="center" prop="birthDate" width="100" />
      <el-table-column label="工作单位" align="center" prop="workUnit" width="150" />
      <el-table-column label="申报职业" align="center" prop="appliedProfession" width="120" />
      <el-table-column label="申报等级" align="center" prop="appliedLevel" width="80" />
      <el-table-column label="工作年限" align="center" prop="workYears" width="80">
        <template #default="scope">
          {{ scope.row.workYears || 0 }}年
        </template>
      </el-table-column>
      <el-table-column label="报名状态" align="center" prop="registrationStatus" width="80">
        <template #default="scope">
          <el-tag :type="getRegistrationStatusTagType(scope.row.registrationStatus)">
            {{ getRegistrationStatusText(scope.row.registrationStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" width="200" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openDetail(scope.row.id)"
            v-hasPermi="['eval:candidate:query']"
          >
            详情
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['eval:candidate:update']"
          >
            编辑
          </el-button>
          <el-dropdown @command="(command) => handleCommand(command, scope.row)">
            <el-button link type="primary">
              更多<Icon icon="ep:arrow-down" class="ml-5px" />
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="audit" v-if="scope.row.auditStatus === 0">
                  审核
                </el-dropdown-item>
                <el-dropdown-item command="materials">
                  材料管理
                </el-dropdown-item>
                <el-dropdown-item command="delete">
                  删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <CandidateForm ref="formRef" @success="getList" />
  
  <!-- 详情弹窗 -->
  <CandidateDetail ref="detailRef" />
  
  <!-- 审核弹窗 -->
  <CandidateAudit ref="auditRef" @success="getList" />
  
  <!-- 批量审核弹窗 -->
  <CandidateBatchAudit ref="batchAuditRef" @success="getList" />
  
  <!-- 材料管理弹窗 -->
  <CandidateMaterials ref="materialsRef" />
  
  <!-- 导入弹窗 -->
  <ImportForm ref="importRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import { DICT_TYPE } from '@/utils/dict'
import {
  EvalCandidateInfoVO,
  EvalCandidateInfoPageReqVO,
  getCandidateInfoPage,
  deleteCandidateInfo,
  exportCandidateInfo
} from '@/api/eval/candidate/index'
import { EvalPlanVO, getPlanListByStatus } from '@/api/eval/plan'
import CandidateForm from './CandidateForm.vue'
import CandidateDetail from './CandidateDetail.vue'
import CandidateAudit from './CandidateAudit.vue'
import CandidateBatchAudit from './CandidateBatchAudit.vue'
import CandidateMaterials from './CandidateMaterials.vue'
import ImportForm from './ImportForm.vue'

/** 参评人员 列表 */
defineOptions({ name: 'EvalCandidate' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<EvalCandidateInfoVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const multipleSelection = ref<EvalCandidateInfoVO[]>([]) // 多选数据
const queryParams = reactive<EvalCandidateInfoPageReqVO>({
  pageNo: 1,
  pageSize: 10,
  planId: undefined,
  name: undefined,
  idNumber: undefined,
  mobile: undefined,
  appliedProfession: undefined,
  appliedLevel: undefined,
  registrationStatus: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const planList = ref<EvalPlanVO[]>([]) // 计划列表

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await getCandidateInfoPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: EvalCandidateInfoVO[]) => {
  multipleSelection.value = selection
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 详情操作 */
const detailRef = ref()
const openDetail = (id: number) => {
  detailRef.value.open(id)
}

/** 审核操作 */
const auditRef = ref()
const openAudit = (id: number) => {
  auditRef.value.open(id)
}

/** 批量审核操作 */
const batchAuditRef = ref()
const openBatchAudit = () => {
  const ids = multipleSelection.value.map(item => item.id!)
  batchAuditRef.value.open(ids)
}

/** 材料管理操作 */
const materialsRef = ref()
const openMaterials = (candidateData: EvalCandidateInfoVO) => {
  materialsRef.value.open(candidateData)
}

/** 导入操作 */
const importRef = ref()
const handleImport = () => {
  importRef.value.open()
}

/** 更多操作 */
const handleCommand = async (command: string, row: EvalCandidateInfoVO) => {
  switch (command) {
    case 'audit':
      openAudit(row.id!)
      break
    case 'materials':
      openMaterials(row)
      break
    case 'delete':
      await handleDelete(row.id!)
      break
  }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await deleteCandidateInfo(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await exportCandidateInfo(queryParams)
    download.excel(data, '参评人员.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 获取报名状态标签类型 */
const getRegistrationStatusTagType = (status: number) => {
  const typeMap = { 1: 'warning', 2: 'success', 3: 'danger' }
  return typeMap[status] || ''
}

/** 获取报名状态文本 */
const getRegistrationStatusText = (status: number) => {
  const textMap = { 1: '已报名', 2: '已确认', 3: '已取消' }
  return textMap[status] || '未知'
}

/** 加载计划列表 */
const loadPlanList = async () => {
  try {
    // 获取已发布和进行中的计划
    const publishedPlans = await getPlanListByStatus(3)
    const inProgressPlans = await getPlanListByStatus(4)
    planList.value = [...publishedPlans, ...inProgressPlans]
  } catch (error) {
    console.error('加载计划列表失败:', error)
  }
}

/** 初始化 **/
onMounted(() => {
  loadPlanList()
  getList()
})
</script>
